<?php

namespace App\Http\Controllers;


use App\Models\Member;
use Auth;
use Kalnoy\Nestedset\Collection;
use Request;

class SelfAuthController extends Controller
{
    public function getEasyWechatSession()
    {
        /** @var Collection $user */
        $user = session('wechat.oauth_user.default');
        return $user;
    }

    public function autoLogin()
    {
        $userInfo = $this->getEasyWechatSession();
        $openId   = $userInfo['id'];
        //查看对应的openid是否已被注册
        $userModel = Member::where('openid', $openId)->first();
        //如果未注册，跳转到注册
        if (!$userModel) {
            return redirect()->route('register', ['redirect' => Request::get('redirect')]);
        } else {
            //如果已被注册，通过openid进行自动认证，
            //认证通过后重定向回原来的路由，这样就实现了自动登陆。
            $token = Auth::guard('api')->login($userModel);

            $redirect = Request::get('redirect');
            $redirect .= (str_contains($redirect, '?') ? '&' : '?') . 'token=' . $token;
            return redirect()->intended($redirect);
        }
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function autoRegister()
    {
        session()->forget('wechat.oauth_user');
        return redirect()->route('wechat_register', ['redirect' => Request::get('redirect')]);
    }

    public function register(){
        $we_user = $this->getEasyWechatSession();
        //根据微信信息注册用户。

        $member = Member::whereOpenid($we_user['id'])->first();
        if (!$member instanceof Member) {
            $userData = [
                'openid'   => $we_user->id,
                'name'     => $we_user->name,
                'nickname' => $we_user->nickname,
                'avatar'   => $we_user->avatar,
                'email'    => $we_user->email,
                'sex'      => isset($we_user->original['sex']) ? $we_user->original['sex'] : null,
                'city'     => isset($we_user->original['city']) ? $we_user->original['city'] : null,
                'province' => isset($we_user->original['province']) ? $we_user->original['province'] : null,
            ];
            //注意批量写入需要把相应的字段写入User中的$fillable属性数组中
            $member = Member::create($userData);
        }

        if (!$member->is_authorized && $we_user->original) {
            $member->name ? $member->name = $we_user->name : '';
            $member->avatar ? $member->avatar = $we_user->avatar : '';
            $member->nickname = $we_user->nickname;
            $member->name = $we_user->email;
            $member->sex           = isset($we_user->original['sex']) ? $we_user->original['sex'] : null;
            $member->city          = isset($we_user->original['city']) ? $we_user->original['city'] : null;
            $member->province      = isset($we_user->original['province']) ? $we_user->original['province'] : null;
            $member->is_authorized = true;
            $member->save();
        }

        $token    = Auth::guard('api')->login($member);
        $redirect = Request::get('redirect');
        $redirect .= (str_contains($redirect, '?') ? '&' : '?') . 'token=' . $token;
        return redirect()->intended($redirect);
    }
}